package com.lungle.warmdiary.app.view.me.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.Image;
import com.lungle.warmdiary.app.utils.LoadLocalImageUtil;
import com.lungle.warmdiary.app.utils.TDevice;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 添加头像
 * Created by zhangxueyuan on 16/9/26.
 */
public class AddIconFragment extends BaseFragment {
    private static final String ADD_ICON = "add icon ";
    private final int CODE_SELECT = 1;
    public static final String ICON_PATH = "icon_path";

    @Bind(R.id.iv_friend)
    ImageView mIvFriend;

    private String imgPath;
    private String mIcon;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_icon, container, false);
        initData();
        initViews(view);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(ADD_ICON);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(ADD_ICON);
        MobclickAgent.onPause(getActivity());

    }

    @Override
    public void initData() {
        mIcon = getArguments().getString(ICON_PATH);
    }


    private void initViews(View view) {
        ButterKnife.bind(this, view);

        if (!TextUtils.isEmpty(mIcon)) {
            ImageLoader.getInstance().displayImage(mIcon, mIvFriend);
            imgPath = mIcon;
        }


    }


    @OnClick(R.id.iv_friend)
    public void onClick(View view) {
        TDevice.hideSoftKeyboard(view);
//        PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
//        intent.setPhotoCount(1);
//        intent.setShowCamera(false);
//        startActivityForResult(intent, CODE_SELECT);
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(false)
                .start(getActivity(), this, CODE_SELECT);

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            ArrayList<String> images = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (!images.isEmpty()) {
                imgPath = images.get(0);
                display(imgPath);
            }
        }
    }


    private void display(String url) {
        LoadLocalImageUtil.getInstance().displayFromSDCard(url, mIvFriend);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);
        menu.findItem(R.id.login_menu_send);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (prepareSubmit()) {
            File file = new File(imgPath);
            uploadAndUpdate(file);
        }


        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private boolean prepareSubmit() {

        if (TextUtils.isEmpty(imgPath)) {
            AppContext.showToast("请选头像");
            return false;

        }
        return true;

    }


    private void setResultData(String url) {
        Intent intent = new Intent();
        intent.putExtra(ICON_PATH, url);
        getActivity().setResult(MediaAddResultFragment.RESULT_OK, intent);
    }


    private void uploadAndUpdate(File file) {
        showWaitDialog("正在上传...");
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        ApiFactory.getFileApi().upload(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Image>>(getActivity()) {

                    @Override
                    public void onNext(Result<Image> imageResult) {
                        String url = imageResult.getData().getUrl();
                        setResultData(url);
                    }

                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        getActivity().finish();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                        e.printStackTrace();
                        AppContext.showToast("上传失败");

                    }
                });
    }

}

